<?php

namespace App\Http\Models;


use Illuminate\Support\Facades\DB;

class Article extends BosModel
{
    use SafeSave;
    protected $guarded = [''];

    protected $bosKeyPrefix = 'bym-admin/article/';

    protected $table = 'articles';

    public function setThumbAttribute($data)
    {
        if(!!$data) {
            $bosKey = $this->uploadImages($data,'article/thumb/');
            $this->attributes['thumb'] = $bosKey;
        }
    }

    public function getThumbAttribute()
    {

        if (!!$this->attributes['thumb'])
        {
            return $this->getUrl($this->attributes['thumb']);
        }

    }

    public function setBannerAttribute($data)
    {
        if(!!$data && !is_string($data)) {
//            if ( is_string($data) )  $this->attributes['banner'] = $data;
            $bosKey = $this->uploadImages($data,'article/banner/');
            $this->attributes['banner'] = $bosKey;
        }else{
            $this->attributes['banner'] = $data;
        }
    }

    public function getBannerAttribute()
    {

        if (!!$this->attributes['banner'])
        {
            return $this->getUrl($this->attributes['banner']);
        }

    }

    public function setCarouselFigureAttribute($data)
    {
        if(!!$data) {
            $bosKey = $this->uploadImages($data,'article/carousel_figure/');
            $this->attributes['carousel_figure'] = $bosKey;
        }
    }

    public function getCarouselFigureAttribute()
    {

        if (!!$this->attributes['carousel_figure'])
        {
            return $this->getUrl($this->attributes['carousel_figure']);
        }

    }

    public function setCompanyThumbAttribute($data)
    {
        if(!!$data) {
            $bosKey = $this->uploadImages($data,'article/company_thumb/');
            $this->attributes['company_thumb'] = $bosKey;
        }
    }

    public function getCompanyThumbAttribute()
    {

        if (!!$this->attributes['company_thumb'])
        {
            return $this->getUrl($this->attributes['company_thumb']);
        }

    }

    public function scopeArticleTagId($query,$tag_id)
    {
        $tag = ArticleTag::find($tag_id);

        $article_ids = $tag->articles->pluck('id');

        if ( count($article_ids)==0 )
        {
            $article_ids = DB::table('article_pivot_tag')->whereIn('article_tag_id',$tag->tags->pluck('id'))->pluck('article_id');
        }

        return $query->whereIn( 'id' , $article_ids );
    }

    public function articleTags()
    {
        return $this->belongsToMany(ArticleTag::class,'article_pivot_tag','article_id','article_tag_id');
    }

}
